/*
 * @Author: CodeHare
 * @Date: 2023-10-09 09:39:35
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-04-25 15:15:56
 * @Description: 站点数据总览页
 */
// ignore_for_file: avoid_function_literals_in_foreach_calls

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yt_devops/components/event_bus_util/eventbus_util.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/new_air_cooling_page/component/char_x.dart';
import 'package:yt_devops/pages/site/site_statis_data/site_statis_data_model.dart';
import 'package:yt_devops/pages/site/site_tab/site_tab_controller.dart';
import 'package:yt_devops/pages/site/widgets/power_rank_tab.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/site/site_services.dart';
import 'package:yt_devops/utils/enums.dart';

class SiteStatisDataController extends GetxController
    with GetTickerProviderStateMixin {
  SiteTabController siteTabController = Get.find<SiteTabController>();
  RefreshController refreshController =
      RefreshController(initialRefresh: false);
  final SiteServices siteServices = Get.find<SiteServices>();
  final SiteStatisDataModel state = SiteStatisDataModel();
  StatisticsWithinTheSite siteStatisticsDataModel = StatisticsWithinTheSite();
  StatisticUnitStatusType statisticUnitType = StatisticUnitStatusType.day;

  /// 目标展示时间
  late DateTime target;

  /// 目标时间
  late int targetYear;
  late int targetMonth;
  late int targetDay;
  List<dynamic> originData = []; //原始的曲线数据
  /// 1 今日光伏自发电量 光伏发电	2储能充电量 储能放电量  3充电桩充电量 	4负载用电量  	5市电电量
  List<dynamic> pvPowerGeneration = []; //光伏发电 pv
  List<dynamic> energyStorageCharge = []; //储能系统 es
  List<dynamic> cpCharge = []; //充电桩充电 cs
  List<dynamic> loadUse = []; //负载用电 load
  List<dynamic> mainUse = []; //市电用电 me
  List timeList = ChartXDate.getData(timeInterval: 2);
  int remainder = 1; //每4小时展示一个坐标点
  List eChartPowerShowList = []; //展示的每日功率概览
  List eChartPowerDetailShowList = []; //展示的每日功率详情
  List eChartPowerOverviewList = []; //每日功率概览
  List eChartPowerDetailList = []; //每日功率详情
  List eChartAllDayPowerOriginList = []; //日线图 包涵所有设备

  Map<String, dynamic> energyData = {};
  var energyOptions = '123';
  var siteName = '';
  bool isFirstLoading = true;
  PowerRankTabType selectedType = PowerRankTabType.power;
  late TabController tabController;
  List<dynamic> powerData = [];
  bool isOverview = true; //是否是概览
  Map<String, dynamic> allDataMap = {};
  bool isShowMain = false;
  bool isShowPv = false;

  /// 1 今日光伏自发电量 光伏发电	2储能充电量 储能放电量  3充电桩充电量 	4负载用电量  	5市电电量
  bool isShowEs = false;
  bool isShowCharge = false;
  bool isShowLoad = false;
  final GlobalKey showTitlesKey = GlobalKey();
  final GlobalKey electricityTitlesKey = GlobalKey();
  double showTitlesContainerHeight = 20;
  double showElectricityHeight = 20;
  int subType = 0; //subType为0时 0为功率曲线 1为电量
  List electricityBarChartList = []; //电量
  List eChartElectricityShowList = []; //展示的电量
  List barProfitList = []; //收益
  List emptyDataList = []; //收益
  // num profitMaxValue = 1;
  // num profitMinValue = 0;
  // num electricityMaxValue = 1;
  // num electricityMinValue = 0;
  List<dynamic> powerXAxisList = []; //功率x轴数据
  List<dynamic> electricityXAxisList = []; //电量x轴数据
  List<dynamic> profitXAxisList = []; //收益x轴数据
  // List<num> electricityMaxMinList = []; //电量最大最小值
  // List<num> profitMaxMinList = []; //电量最大最小值
  String monetaryUnitName = '';
  @override
  void onInit() {
    super.onInit();
    tabController = TabController(length: 3, vsync: this);
    if (Get.arguments != null && Get.arguments['energyOptions'] != null) {
      energyOptions = Get.arguments['energyOptions'].toString();

    }
    if (Get.arguments != null && Get.arguments['monetaryUnitName'] != null) {
      monetaryUnitName = Get.arguments['monetaryUnitName'];
      if(monetaryUnitName == '元' || monetaryUnitName == '¥'){
        monetaryUnitName = ResKey.yuan.tr;
      }
    }
    Log.d('monetaryUnitName===' + monetaryUnitName);
    siteName = Get.arguments['siteName'].toString();
    electricityXAxisList = ChartXDate.getHoursData();
    initData();
    EventBusUtil.getInstance().on<ChangeMonetaryUnit>().listen((event) {
      GetStorage storage = GetStorage();
      String storeMonetaryUnitName = storage.read('monetaryUnitName')??'元';
      monetaryUnitName = storeMonetaryUnitName;
      if(monetaryUnitName == '元' || monetaryUnitName == '¥'){
        monetaryUnitName = ResKey.yuan.tr;
      }
      onRefresh();
    });
  }

  @override
  void onReady() {
    // Log.d('allDataMap==');
    onRefresh();
    loadSiteDayStatisticsDetail();
  }

  initData() {
    initCurrentDate();
    for (int i = 0; i < timeList.length; i++) {
      var element = timeList[i];
      List tempList = [];
      tempList.add(element.substring(11, 16));
      tempList.add('--');
      powerXAxisList.add(element.substring(11, 16));
      originData.add(tempList);
    }
    emptyDataList.add({});
  }

  List<dynamic> _showData1(
    List originList,
  ) {
    List<dynamic> returnList = [];
    for (int i = 0; i < originList.length; i++) {
      var element = originList[i];
      if (i % 1 == 0) {
        returnList.add(element);
      }
    }
    return returnList;
  }

  List<dynamic> _handleData(List originList, List? dataList) {
    List<dynamic> returnList = [];

    if (dataList != null && dataList.isNotEmpty) {
      Map map = {};
      for (var element in dataList) {
        map[element['eventTs'].substring(11, 16)] = element['doubleVal'];
      }
      for (var element in originList) {
        List<dynamic> elementList = List.from(element);
        if (map[elementList[0]] != null) {
          elementList[1] = map[elementList[0]].toString();
        }
        returnList.add(elementList[1]);
      }
    } else {
      if (originList != null && originList.isNotEmpty) {
        originList.forEach((element) {
          returnList.add(element[1]);
        });
      }

      // returnList = List.from(originList);
    }

    return returnList;
  }

  /// @description:  请求参数
  /// @return {*}
  Map<String, dynamic> _collectParams() {
    String month = targetMonth.toString();
    if (targetMonth < 10) {
      month = '0$targetMonth';
    }
    String day = targetDay.toString();
    if (targetDay < 10) {
      day = '0$targetDay';
    }
    return {
      'siteId': siteTabController.siteId,
      'date': '$targetYear-$month-$day',
      'type': statisticUnitType.value,
      'subType': subType,
      'time':'$targetYear-$month-$day',
      // 'isConfine': 0
    };
  }

  ///获取储能概览
  getOverviewStatistics() async {
    // showLoading(toast: ResKey.loading.tr);
    var result = await siteServices.getEsOverviewStatistics(_collectParams(),
        onError: (error) {
      // dismissLoading();
      handleException(error);
      return false;
    });
    // dismissLoading();
    if (result != null) {
      energyData = result;
      update();
    }
  }

  getSiteOverviewGainsStatistics() async {
    // var params = {
    //   'siteId': siteTabController.siteId,
    //   'type': statisticUnitType.value,
    // };
    // showLoading(toast: ResKey.loading.tr);
    var data = await siteServices.getSiteOverviewGainsStatistics(_collectParams(),
        onError: (error) {
      // dismissLoading();
      // showError(error.message.toString());
      return false;
    });
    // dismissLoading();
    if (data != null) {
      energyData = data;
      update();
    }
    Log.d('data===$data');
  }

  ///获取功率的详细指标数据
  loadSiteDayStatisticsDetail() async {
    var params = _collectParams();
    // showLoading(toast: ResKey.loading.tr);
    var data = await siteServices.getSiteAllDayPower(params, onError: (error) {
      // dismissLoading();
      // showError(error.message.toString());
      return false;
    });
    dismissLoading();

    /// 1 今日光伏自发电量 光伏发电	2储能充电量 储能放电量  3充电桩充电量 	4负载用电量  	5市电电量
    if (data != null) {
      if (data['flag'] != null) {
        electricityBarChartList.clear();
        eChartPowerDetailShowList.clear();
        List tempList = data['flag'];
        tempList.forEach((element) {
          if (element['flag'] == true) {
            /// 1 今日光伏自发电量 光伏发电	2储能充电量 储能放电量  3充电桩充电量 	4负载用电量  	5市电电量
            if (element['code'] == 1) {
              pvPowerGeneration = List.from(originData);
              isShowPv = true;
            } else if (element['code'] == 2) {
              energyStorageCharge = List.from(originData);
              isShowEs = true;
            } else if (element['code'] == 3) {
              cpCharge = List.from(originData);
              isShowCharge = true;
            } else if (element['code'] == 4) {
              loadUse = List.from(originData);
              isShowLoad = true;
            } else if (element['code'] == 5) {
              mainUse = List.from(originData);
              isShowMain = true;
            }
          }
        });
      }

      allDataMap = data['powers'];
      // Log.d('allDataMap==' + allDataMap.toString());
      handlePowerData();

      update();
    }
  }

  changeShowTitleHeight() {
    ///这里需要做延迟加载 不然无法得到context的真实高度
    Future.delayed(const Duration(milliseconds: 200), () {
      // 延迟执行的代码
      if (showTitlesKey.currentContext != null) {
        showTitlesContainerHeight = showTitlesKey.currentContext!.size!.height;
        Log.d('showTitlesContainerHeight==' +
            showTitlesContainerHeight.toString());
        update();
      }
    });
  }

  /// @description: 请求站点内统计数据
  /// @return {*}
  loadSiteDataStatistics() async {
    var params = _collectParams();
    if(isFirstLoading)showLoading(toast: ResKey.loading.tr);
    var data =
        await siteServices.getSiteDataStatisticsNew(params, onError: (error) {
      dismissLoading();
      isFirstLoading = false;
      showError(error.message.toString());
      return false;
    });
    dismissLoading();
    isFirstLoading = false;
    if (data != null) {
      // Log.d('data=====' + data.toString());
      if (statisticUnitType == StatisticUnitStatusType.day &&
          selectedType == PowerRankTabType.power) {
        eChartPowerShowList.clear();
        state.chartShowTitles.clear();
        if (data['me'] != null) {
          Map map = data['me'];
          if (map['flag'] != null && map['flag'] == true) {
            _addEChartData(map['name'].toString(), List.from(originData),
                map['data'] ?? [],
                colorString: map['color'] ?? '#FAC958');
          }
        }
        if (data['pv'] != null) {
          Map map = data['pv'];
          if (map['flag'] != null && map['flag'] == true) {
            _addEChartData(map['name'].toString(), List.from(originData),
                map['data'] ?? [],
                colorString: map['color'] ?? '#FAC958');
          }
        }
        if (data['es'] != null) {
          Map map = data['es'];
          if (map['flag'] != null && map['flag'] == true) {
            _addEChartData(map['name'].toString(), List.from(originData),
                map['data'] ?? [],
                colorString: map['color'] ?? '#FAC958');
          }
        }
        if (data['cs'] != null) {
          Map map = data['cs'];
          if (map['flag'] != null && map['flag'] == true) {
            _addEChartData(map['name'].toString(), List.from(originData),
                map['data'] ?? [],
                colorString: map['color'] ?? '#FAC958');
          }
        }
        if (data['load'] != null) {
          Map map = data['load'];
          if (map['flag'] != null && map['flag'] == true) {
            _addEChartData(map['name'].toString(), List.from(originData),
                map['data'] ?? [],
                colorString: map['color'] ?? '#FAC958');
          }
        }
        // Log.d('eChartPowerShowList==' + eChartPowerShowList.toString());
        eChartPowerOverviewList = List.from(eChartPowerShowList);
        update();
      } else {
        electricityBarChartList.clear();
        eChartElectricityShowList.clear();
        state.showElectricityTitles.clear();
        if (data['mainsUse'] != null) {
          Map map = data['mainsUse'];
          if (map['flag'] != null && map['flag'] == true) {
            _addElectricityBarEChartData(map['name'].toString(),
                _handleBarData(map['data'] ?? [], statisticUnitType.value),
                colorString: map['color'] ?? '#FAC958');
          }
        }
        if (data['pvSelfUse'] != null) {
          Map map = data['pvSelfUse'];
          if (map['flag'] != null && map['flag'] == true) {
            _addElectricityBarEChartData(map['name'].toString(),
                _handleBarData(map['data'] ?? [], statisticUnitType.value),
                colorString: map['color'] ?? '#FAC958');
          }
        }
        if (data['pvPowerGeneration'] != null) {
          Map map = data['pvPowerGeneration'];
          if (map['flag'] != null && map['flag'] == true) {
            _addElectricityBarEChartData(map['name'].toString(),
                _handleBarData(map['data'] ?? [], statisticUnitType.value),
                colorString: map['color'] ?? '#FAC958');
          }
        }
        if (data['essCharge'] != null) {
          Map map = data['essCharge'];
          if (map['flag'] != null && map['flag'] == true) {
            _addElectricityBarEChartData(map['name'].toString(),
                _handleBarData(map['data'] ?? [], statisticUnitType.value),
                colorString: map['color'] ?? '#FAC958');
          }
        }
        if (data['essDischarge'] != null) {
          Map map = data['essDischarge'];
          if (map['flag'] != null && map['flag'] == true) {
            _addElectricityBarEChartData(map['name'].toString(),
                _handleBarData(map['data'] ?? [], statisticUnitType.value),
                colorString: map['color'] ?? '#FAC958');
          }
        }
        if (data['cpCharge'] != null) {
          Map map = data['cpCharge'];
          if (map['flag'] != null && map['flag'] == true) {
            _addElectricityBarEChartData(map['name'].toString(),
                _handleBarData(map['data'] ?? [], statisticUnitType.value),
                colorString: map['color'] ?? '#FAC958');
          }
        }
        if (data['loadUse'] != null) {
          Map map = data['loadUse'];
          if (map['flag'] != null && map['flag'] == true) {
            _addElectricityBarEChartData(map['name'].toString(),
                _handleBarData(map['data'] ?? [], statisticUnitType.value),
                colorString: map['color'] ?? '#FAC958');
          }
        }
        if (data['gain'] != null) {
          barProfitList.clear();
          Map map = data['gain'];
          if (map['flag'] != null && map['flag'] == true) {
            _addElectricityBarEChartData(map['name'].toString(),
                _handleBarData(map['data'] ?? [], statisticUnitType.value),
                colorString: map['color'] ?? '#FAC958', isProfit: true);
          }
        }
      }
      eChartElectricityShowList = List.from(electricityBarChartList);
      update();
    }
    Log.d('changeShowTitleHeight===11===');
    Future.delayed(const Duration(milliseconds: 200), () {
      // 延迟执行的代码
      if (showTitlesKey.currentContext != null) {
        showTitlesContainerHeight = showTitlesKey.currentContext!.size!.height;
        update();
      }
      if (electricityTitlesKey.currentContext != null) {
        showElectricityHeight =
            electricityTitlesKey.currentContext!.size!.height;
        Log.d('showElectricityHeight==' + showElectricityHeight.toString());
        update();
      }
    });
    // powerOverviewClick();
    /// 1 今日光伏自发电量 光伏发电	2储能充电量 储能放电量  3充电桩充电量 	4负载用电量  	5市电电量
  }

  ///功率概览被点击了
  powerOverviewClick() {
    // if (isOverview) return;
    isOverview = true;

    update();
    changeShowTitleHeight();
  }

  ///功率详情被点击了
  powerDetailClick() {
    if (isOverview == false) return;
    isOverview = false;
    update();
    changeShowTitleHeight();
  }

  handlePowerData() {
    List mainUseList = allDataMap['me'] ?? [];
    List pvPowerGenerationList = allDataMap['pv'] ?? [];
    List energyStorageChargeList = allDataMap['es'] ?? [];
    List cpChargeList = allDataMap['cs'] ?? [];
    List loadUseList = allDataMap['load'] ?? [];
    Log.d('isShowMain==' + mainUseList.length.toString());
    eChartPowerDetailShowList.clear();
    state.chartShowDetailTitles.clear();
    if (isShowMain) {
      if (mainUseList.isNotEmpty) {
        mainUseList.forEach((map) {
          List<dynamic> mainUse = List.from(originData);
          _addEChartData(map['name'].toString(), mainUse, map['data'],
              colorString: map['color'] ?? state.chartLineColor[0],
              yAxis: map['maximumLoadOfTransformer'] != null &&
                      map['maximumLoadOfTransformer']['value'] != null
                  ? map['maximumLoadOfTransformer']['value']
                  : 100000,
              isDetail: true);
        });
      }
    }
    if (isShowPv) {
      if (pvPowerGenerationList.isNotEmpty) {
        pvPowerGenerationList.forEach((map) {
          List<dynamic> mainUse = List.from(originData);
          _addEChartData(map['name'].toString(), mainUse, map['data'],
              colorString: map['color'] ?? state.chartLineColor[1],
              yAxis: map['maximumLoadOfTransformer'] != null &&
                      map['maximumLoadOfTransformer']['value'] != null
                  ? map['maximumLoadOfTransformer']['value']
                  : 100000,
              isDetail: true);
        });
      }
    }
    if (isShowEs) {
      if (energyStorageChargeList.isNotEmpty) {
        energyStorageChargeList.forEach((map) {
          List<dynamic> mainUse = List.from(originData);
          _addEChartData(map['name'].toString(), mainUse, map['data'],
              colorString: map['color'] ?? state.chartLineColor[2],
              yAxis: map['maximumLoadOfTransformer'] != null &&
                      map['maximumLoadOfTransformer']['value'] != null
                  ? map['maximumLoadOfTransformer']['value']
                  : 100000,
              isDetail: true);
        });
      }
    }
    if (isShowCharge) {
      if (cpChargeList.isNotEmpty) {
        cpChargeList.forEach((map) {
          List<dynamic> mainUse = List.from(originData);
          _addEChartData(map['name'].toString(), mainUse, map['data'],
              colorString: map['color'] ?? state.chartLineColor[3],
              yAxis: map['maximumLoadOfTransformer'] != null &&
                      map['maximumLoadOfTransformer']['value'] != null
                  ? map['maximumLoadOfTransformer']['value']
                  : 100000,
              isDetail: true);
        });
      }
    }
    if (isShowLoad) {
      if (loadUseList.isNotEmpty) {
        loadUseList.forEach((map) {
          List<dynamic> mainUse = List.from(originData);
          _addEChartData(map['name'].toString(), mainUse, map['data']??[],
              colorString: map['color'] ?? state.chartLineColor[4],
              yAxis: map['maximumLoadOfTransformer'] != null &&
                      map['maximumLoadOfTransformer']['value'] != null
                  ? map['maximumLoadOfTransformer']['value']
                  : 100000,
              isDetail: true);
        });
      }
    }
    Log.d('eChartPowerDetailShowList==${eChartPowerDetailShowList.length}');
    eChartPowerDetailList = List.from(eChartPowerDetailShowList);
    update();
  }

  _handleBarData(List? data, String statisticUnitTypeString) {
    List result = [];
    if (data != null) {
      data!.forEach((element) {
        String time = element['eventTs'].toString();
        if (statisticUnitTypeString == StatisticUnitStatusType.day.value &&
            element['eventTs'].toString().length > 16) {
          time = element['eventTs'].toString().substring(10, 16);
        } else if (statisticUnitTypeString ==
                StatisticUnitStatusType.month.value &&
            element['eventTs'].toString().length >= 10) {
          time = element['eventTs'].toString().substring(8, 10);
        } else if (statisticUnitTypeString ==
                StatisticUnitStatusType.year.value &&
            element['eventTs'].toString().length >= 7) {
          time = element['eventTs'].toString().substring(5, 7);
        }
        List temp = [
          time,
          element['doubleVal'] != null ? element['doubleVal'].toString() : '--'
        ];
        // result.add(temp);
        result.add(element['doubleVal'] != null
            ? element['doubleVal'].toString()
            : '--');
      });
    }
    return result;
  }

  ///把电量动态添加到图表
  _addElectricityBarEChartData(String title, List originData,
      {String colorString = '#FAC958', bool isProfit = false}) {
    if (originData.isNotEmpty) {
      if (isProfit) {
        // for (var element in originData) {
        //   if(element.toString()!='null' && element.toString()!='--'){
        //     profitMaxMinList.add(num.parse(element.toString()));
        //   }
        // }
        barProfitList.add({
          'name': title,
          'type': 'bar',
          'barMaxWidth': 10,
          'itemStyle': {
            'normal': {'color': colorString, 'barBorderRadius': 11}
          },
          'data': originData
        });
      } else {
        // for (var element in originData) {
        //   if(element.toString()!='null' && element.toString()!='--'){
        //     electricityMaxMinList.add(num.parse(element.toString()));
        //   }
        // }
        state.showElectricityTitles
            .add({'title': title, 'color': colorString, 'isShow': true});
        electricityBarChartList.add({
          'name': title,
          'type': 'bar',
          'barMaxWidth': 10,
          'itemStyle': {
            'normal': {'color': colorString, 'barBorderRadius': 11}
          },
          'data': originData
        });
      }
    }
    Log.d('gain=== ' + barProfitList.toString());
  }

  ///展示或者隐藏电量指标
  hiddenOrShowElectricity(String title) {
    for (var element in state.showElectricityTitles) {
      if (title == element['title']) {
        element['isShow'] = !element['isShow'];
        update();
      }
    }
    var originMap = {};
    for (int i = 0; i < electricityBarChartList.length; i++) {
      var map = electricityBarChartList[i];
      originMap[map['name']] = map;
    }
    eChartElectricityShowList.clear();
    for (int i = 0; i < state.showElectricityTitles.length; i++) {
      var element = state.showElectricityTitles[i];

      if (element['isShow'] == true) {
        eChartElectricityShowList.add(originMap[element['title']]);
      }
    }
  }

  //展示或者隐藏指标
  hiddenOrShowData(String title) {
    Log.d('originMap==' + isOverview.toString());
    if (isOverview) {
      for (var element in state.chartShowTitles) {
        if (title == element['title']) {
          element['isShow'] = !element['isShow'];
          update();
        }
      }
      var originMap = {};
      for (int i = 0; i < eChartPowerOverviewList.length; i++) {
        var map = eChartPowerOverviewList[i];
        originMap[map['name']] = map;
      }
      eChartPowerShowList.clear();
      for (int i = 0; i < state.chartShowTitles.length; i++) {
        var element = state.chartShowTitles[i];

        if (element['isShow'] == true) {
          eChartPowerShowList.add(originMap[element['title']]);
        }
      }
    } else {
      for (var element in state.chartShowDetailTitles) {
        if (title == element['title']) {
          element['isShow'] = !element['isShow'];
          update();
        }
      }
      var originMap = {};
      for (int i = 0; i < eChartPowerDetailList.length; i++) {
        var map = eChartPowerDetailList[i];
        originMap[map['name']] = map;
      }
      Log.d('originMap==' + originMap.toString());
      eChartPowerDetailShowList.clear();
      for (int i = 0; i < state.chartShowDetailTitles.length; i++) {
        var element = state.chartShowDetailTitles[i];

        if (element['isShow'] == true) {
          eChartPowerDetailShowList.add(originMap[element['title']]);
        }
      }
    }

    update();
  }

  ///把日功率数据动态添加到图表
  _addEChartData(String title, List originData, List realData,
      {String colorString = '#FAC958',
      double yAxis = 100000,
      bool isDetail = false}) {
    if (originData.isNotEmpty) {
      originData = _handleData(originData, realData);

      if (isDetail) {
        state.chartShowDetailTitles
            .add({'title': title, 'color': colorString, 'isShow': true});
        eChartPowerDetailShowList.add({
          'name': title,
          'type': 'line',
          'smooth': false,
          'symbol': "none", // 这里隐藏了折线图中的圆点
          'color': colorString,
          'markLine': {
            'symbol': "none", // 这里隐藏了折线图中的圆点
            'data': [
              {
                'name': '水平线',
                'yAxis': yAxis,
              },
            ],
            'silent': true,
            'lineStyle': {
              'color': colorString,
            }
          },
          'data': originData
        });
      } else {
        state.chartShowTitles
            .add({'title': title, 'color': colorString, 'isShow': true});
        eChartPowerShowList.add({
          'name': title,
          'type': 'line',
          'smooth': false,
          'symbol': "none", // 这里隐藏了折线图中的圆点
          'color': colorString,
          'markLine': {
            'symbol': "none", // 这里隐藏了折线图中的圆点
            'data': [
              {
                'name': '水平线',
                'yAxis': yAxis,
              },
            ],
            'silent': true,
            'lineStyle': {
              'color': colorString,
            }
          },
          'data': originData
        });
      }
    }
    // Log.d('eChartPowerShowList===' + eChartPowerShowList.length.toString());
  }

  /// @description: 赋值光伏发电量
  /// @return {*}
  void assignPvEnergy() {
    state.pvPowerGeneration.clear();
    state.pvPowerGeneration = siteStatisticsDataModel.pvPowerGeneration!;
  }

  /// @description: 收集光伏能量值
  /// @return {*}
  void collectPvEnergy() {
    state.pvPowerGenerationList.clear();

    if (state.activeMonth) {
      for (var i = 0; i < state.pvPowerGeneration.length; i++) {
        state.pvPowerGenerationList.add([
          state.pvPowerGeneration[i].getMonthDayDimension,
          state.pvPowerGeneration[i].electricity,
          state.pvPowerGeneration[i].amount,
        ]);
      }
    } else if (state.activeYear) {
      for (var i = 0; i < state.pvPowerGeneration.length; i++) {
        state.pvPowerGenerationList.add([
          state.pvPowerGeneration[i].getTimeDimension,
          state.pvPowerGeneration[i].electricity,
          state.pvPowerGeneration[i].amount,
        ]);
      }
    } else {
      for (var i = 0; i < state.pvPowerGeneration.length; i++) {
        state.pvPowerGenerationList.add([
          state.pvPowerGeneration[i].getTimeDimension,
          state.pvPowerGeneration[i].electricity,
          state.pvPowerGeneration[i].amount,
        ]);
      }
    }
    Log.d("12 == ${state.pvPowerGenerationList}");
    update();
  }

  /// @description: 时间选择器选择后回显时间到按钮
  /// @return {*}
  void echoDateAssign(DateTime date, StatisticUnitStatusType? statusType) {
    target = date;
    targetYear = target.year;
    targetMonth = target.month;
    targetDay = target.day;

    onClickTab(statusType);

    onRefresh();
    loadSiteDayStatisticsDetail();
    update();
  }

  /// @description: 切换年、月、日、累计按钮
  /// @return {*}
  void onClickTab(StatisticUnitStatusType? status) {
    updateTabUI(status);
    if (statisticUnitType != StatisticUnitStatusType.day &&
        selectedType == PowerRankTabType.power) {
      Log.d('selectedType==111=$selectedType');
      selectedType = PowerRankTabType.electricity;
      tabController.animateTo(selectedType.index);
      update();
    }
  }

  /// @description: 更新Tab样式
  /// @return {*}
  void updateTabUI(StatisticUnitStatusType? status) {
    switch (status) {
      case StatisticUnitStatusType.month:
        activeMonth();
        break;

      case StatisticUnitStatusType.year:
        activeYear();
        break;

      case StatisticUnitStatusType.accumulate:
        activeAccumulate();
        break;

      default:
        activeDay();
    }

    update();
  }

  /// @description: 激活日按钮
  /// @return {*}
  void activeDay() {
    statisticUnitType = StatisticUnitStatusType.day;
    state.pickerMode = DateTimePickerMode.day;
    electricityXAxisList = ChartXDate.getHoursData();
  }

  /// @description: 激活月按钮
  /// @return {*}
  void activeMonth() {
    statisticUnitType = StatisticUnitStatusType.month;
    state.pickerMode = DateTimePickerMode.month;
    electricityXAxisList = ChartXDate.getMonthData();
  }

  /// @description: 激活年按钮
  /// @return {*}
  void activeYear() {
    statisticUnitType = StatisticUnitStatusType.year;
    state.pickerMode = DateTimePickerMode.year;
    electricityXAxisList = ChartXDate.getYearData();
  }

  /// @description: 激活累计按钮
  /// @return {*}
  void activeAccumulate() {
    // state.activeDay = false;
    // state.activeMonth = false;
    // state.activeYear = false;
    // state.activeAccumulate = true;
    statisticUnitType = StatisticUnitStatusType.accumulate;
    state.pickerMode = DateTimePickerMode.year;
    electricityXAxisList = ChartXDate.getTotalData();
  }

  /// @description: 单位数前置加零
  /// @return {*}
  String addLeadingZero(String? value) {
    if (value!.length == 1) {
      return '0$value';
    }
    return value;
  }

  /// @description: 初始化当前日期
  /// @return {*}
  void initCurrentDate() {
    target = DateTime.now();
    targetYear = target.year;
    targetMonth = target.month;
    targetDay = target.day;
  }

  /// @description: 下拉刷新
  /// @return {*}
  void onRefresh() {
    ///如果是储能调用储能接口
    // if (energyOptions == '2') {
    //   getOverviewStatistics();
    // } else {
      getSiteOverviewGainsStatistics();
    // }
    Log.d('onRefresh==');
    loadSiteDataStatistics();
    endRefresh();
  }

  tabClick(PowerRankTabType type) {
    if (type == selectedType) return;
    selectedType = type;
    tabController.animateTo(type.index);
    if (type == PowerRankTabType.power) {
      subType = 0;
    } else {
      subType = 1;
    }
    onRefresh();
    update();
  }

  /// @description: 刷新结束
  /// @return {*}
  void endRefresh() {
    if (refreshController.isRefresh) {
      refreshController.refreshCompleted();
    }
  }
}
